#include "uploadwidget.h"
#include "ui_uploadwidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include "mymessagebox.h"

UploadWidget::UploadWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UploadWidget)
{
    ui->setupUi(this);

    setWindowTitle("批处理");

    thread = new QThread();
    importThread = new ExcelImportThread();
    importThread->moveToThread(thread);

    connect(&productService, &ProductService::uploadProductsSuccess, this, &UploadWidget::dealUploadSuccess);

    connect(&userRelationService, &UserRelationService::uploadUserRelationSuccess, this, &UploadWidget::dealUploadSuccess);

    connect(this, &UploadWidget::importData, importThread, &ExcelImportThread::importData);

    connect(importThread, &ExcelImportThread::importDataDone,
            [=](QList<QList<QVariant>> data)
    {
        this->dealImportData(data);
    });

    connect(this, &UploadWidget::destroyed,
            [=]()
    {
        thread->quit();
        thread->wait();
        delete thread;
    });
}

UploadWidget::~UploadWidget()
{
    delete ui;
}

void UploadWidget::setWidgetType(int widgetType){
    this->widgetType = widgetType;

    switch (widgetType) {
    case 0:
        ui->labelUploadTitle->setText("商品导入");
        break;
    case 1:
        ui->labelUploadTitle->setText("客户导入");
        break;
    case 2:
        ui->labelUploadTitle->setText("供应商导入");
        break;
    }
}

void UploadWidget::showAndInit(){
    ui->labelImportState->setText("文件解析：等待用户选择文件");
    ui->pushButtonUpload->setEnabled(false);
    ui->progressBar->setValue(0);

    exec();
}

void UploadWidget::on_pushButtonOpenFile_clicked()
{
    QString path = QFileDialog::getOpenFileName(
                this,
                "导入商品",
                "../",
                "source(*.xls *.xlsx)");

    if(!path.isEmpty()){
        qDebug()<<path.toUtf8().data();
        if(thread->isRunning() == false){
            thread->start();
        }
        ui->labelImportState->setText("文件解析：解析中...");
        importThread->setFileName(path);
        emit this->importData();
    }
}

void UploadWidget::on_pushButtonUpload_clicked()
{
    curBatch = 0;
    ui->progressBar->setMaximum(totalBatch);
    if(widgetType == 0){
        totalBatch = allProducts.size();
        productService.uploadProduct(
                    this,
                    allProducts[curBatch]);
    }else{
        totalBatch = allRelations.size();
        userRelationService.uploadUserRelation(
                    this,
                    widgetType==1?UserRelation::Client:UserRelation::Giver,
                    allRelations[curBatch]);
    }
}

void UploadWidget::dealImportData(QList<QList<QVariant>> data){
    bool dealRes = false;
    switch (widgetType) {
    case 0:
        qDebug()<<"deal product";
        dealRes = dealProductImportData(data);
        break;
    case 1:
        qDebug()<<"deal client";
        dealRes = dealUserRelationImportData(data, UserRelation::Client);
        break;
    case 2:
        qDebug()<<"deal giver";
        dealRes = dealUserRelationImportData(data, UserRelation::Giver);
        break;
    default:
        qDebug()<<"type error";
        break;
    }

    if(dealRes){
        ui->pushButtonUpload->setEnabled(true);
        ui->labelImportState->setText("文件解析：解析完成");
        MyMessageBox::information("信息", "导入成功！");
    }else{
        ui->labelImportState->setText("文件解析：文件格式错误");
    }
}

bool UploadWidget::dealProductImportData(QList<QList<QVariant>> data){
    if(!productService.checkDataHeader(data.at(0))){
        qDebug()<<"header error";
        MyMessageBox::warning("警告", "导入失败！");
        return false;
    }

    QList<Product*> products = productService.checkData(data);
    if(products.size() != data.size()-1){
        qDebug()<<"size error";
        MyMessageBox::warning("警告", "导入失败！");
        return false;
    }

    qDebug()<<"product size:"<<products.size();

    totalMoney = 0;
    QList<Product*> tempProducts;
    for(int i=0;i<products.size();i++){
        if(i%200==0 && i!=0){
            allProducts.append(tempProducts);
            tempProducts.clear();
        }
        totalMoney += products[i]->count*products[i]->inPrice;
        tempProducts.append(products[i]);
    }
    if(tempProducts.size()!=0){
        allProducts.append(tempProducts);
    }
    totalSize = products.size();

    return true;
}

bool UploadWidget::dealUserRelationImportData(QList<QList<QVariant>> data, UserRelation::RelationType type){
    if(!userRelationService.checkDataHeader(type, data.at(0))){
        MyMessageBox::warning("警告", "导入失败！");
        return false;
    }

    QList<UserRelation*> relations = userRelationService.checkData(type, data);
    if(relations.size() != data.size()-1){
        MyMessageBox::warning("警告", "导入失败！");
        return false;
    }

    QList<UserRelation*> tempRelations;
    for(int i=0;i<relations.size();i++){
        if(i%200==0 && i!= 0){
            allRelations.append(tempRelations);
            tempRelations.clear();
        }
        tempRelations.append(relations[i]);
    }
    if(tempRelations.size()!=0){
        allRelations.append(tempRelations);
    }
    totalSize = relations.size();

    return true;
}

void UploadWidget::dealUploadSuccess(){
    curBatch += 1;
    qDebug()<<curBatch<<"/"<<totalBatch;
    ui->progressBar->setValue(curBatch);
    if(curBatch == totalBatch){
        QMessageBox::information(this, "信息", QString("上传成功%1条记录！").arg(totalSize));
        if(widgetType == 0){
            productService.uploadProductFinished(this, totalMoney);
        }else{
            this->close();
        }
        return ;
    }

    if(widgetType == 0){
        productService.uploadProduct(
                    this,
                    allProducts[curBatch]);
    }else{
        userRelationService.uploadUserRelation(
                    this,
                    widgetType==1?UserRelation::Client:UserRelation::Giver,
                    allRelations[curBatch]);
    }
}
